package com.ansion.commonchat.startup.workmanager.bwork.impl.mode;

import android.text.TextUtils;

import com.ansion.log.LogTag;
import com.ansion.log.VLog;
import com.ansion.utils.GsonUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wanghongjie on 2023/5/5
 * Describe :  BWorkManager 中 Work 之间的依赖关系 ，提供API供外部调用
 */
public class BDependencyImpl implements BDependencyDao {
    private WorkDataCache workDataCache;
    private final List<BDependency> dependencyList = new ArrayList<>();
    private final Map<String, List<String>> dependencyWorkIds = new HashMap<>();
    private final Object mLock = new Object();

    public BDependencyImpl(WorkDataCache workDataCache) {
        this.workDataCache = workDataCache;
    }

    @Override
    public void insertDependency(BDependency dependency) {
        synchronized (mLock) {
            // 原始数据
            dependencyList.add(dependency);
            // key 为 PrerequisiteId , Value 为 workSpecId
            List<String> workSpecIds = dependencyWorkIds.get(dependency.prerequisiteId);
            if (workSpecIds == null) {
                workSpecIds = new ArrayList<>();
                dependencyWorkIds.put(dependency.prerequisiteId, workSpecIds);
            }
            workSpecIds.add(dependency.workSpecId);
            if (VLog.OPEN_LOG)
                VLog.d(LogTag.TAG_B_WORK_MANAGER, " BDependencyDao insertDependency >>   %s ", GsonUtil.GsonString(dependency));
        }
    }

    /**
     * @Query("SELECT COUNT(*)=0 FROM dependency WHERE work_spec_id=:id
     * AND prerequisite_id IN
     * (SELECT id FROM workspec WHERE state!= WorkTypeConverters.StateIds.SUCCEEDED + ")")
     */
    @Override
    public boolean hasCompletedAllPrerequisites(String id) {
        String prerequisiteId = null;
        for (BDependency dependency : dependencyList) {
            if (dependency.workSpecId.equals(id)) {
                prerequisiteId = dependency.prerequisiteId;
                break;
            }
        }
        if (!TextUtils.isEmpty(prerequisiteId)) {
            List<String> unSucceededWorkSpecIds = workDataCache.workSpecDao().getAllUnSucceededWorkSpecIds();
            return unSucceededWorkSpecIds == null || !unSucceededWorkSpecIds.contains(prerequisiteId);
        }
        return true;
    }

    /**
     * @Query("SELECT work_spec_id FROM dependency WHERE prerequisite_id=:id")
     */
    @Override
    public List<String> getDependentWorkIds(String id) {
        List<String> list = dependencyWorkIds.get(id);
        if (list == null) {
            list = new ArrayList<>();
        }
        return list;
    }

    @Override
    public void logout() {
        synchronized (mLock) {
            dependencyList.clear();
            dependencyWorkIds.clear();
        }
    }

}
